/**
 * 工具函数
 */

/* 深度拷贝 */
export function clone(obj: any) {
  const newObj: any = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (obj[key] && typeof obj[key] === 'object') {
        newObj[key] = clone(obj[key])
      } else {
        newObj[key] = obj[key]
      }
    }
  }
  return newObj
}

/* 判断是否为JSON */
export function isJson(str: string) {
  if (typeof str != 'string') {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

/* 数组转为树形数据 */
export function toTree(arr: any[], parentId: number | string, op?: any) {
  const t = []
  op =
    op ||
    function (it: any, pid: number | string) {
      return it.pId == pid || (!pid && !it.pId)
    }
  for (let i = arr.length - 1; i >= 0; --i) {
    const it = arr[i]
    if (op(it, parentId)) {
      t.push(it)
      arr.splice(i, 1)
    }
  }
  t.map((it) => {
    it.children = toTree(arr, it.id, op)
  })
  return t.reverse()
}

/** 生成简单的随机字符串 */
export function getRandomStr() {
  return Math.floor(Math.random() * 10000000).toString(16)
}
